package edu.gatech.ece6102;

import edu.gatech.ece6102.beans.AddressBean;
import edu.gatech.ece6102.beans.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * User: deepal
 * Date: Oct 6, 2010
 * Time: 11:29:26 AM
 */
public class MonitorListener implements Runnable {
    private LogbasedExecutor logbasedExecutor;

    public MonitorListener(LogbasedExecutor logbasedExecutor) {
        this.logbasedExecutor = logbasedExecutor;
        Thread thread = new Thread(this);
        thread.start();
    }

    public void run() {
        try {
            ServerSocket serversocket = new ServerSocket(6666);
            while (!Thread.interrupted()) {
                try {
                    if (serversocket == null || serversocket.isClosed()) {
                        System.out.println("Listening on port " + 6666);
                        serversocket = new ServerSocket(6666);
                        // serversocket.setReuseAddress(true);
                    }
                    Socket socket = serversocket.accept();
                    List<String> values = readData(socket);
                    processList(values);
                } catch (java.io.InterruptedIOException ie) {
                    break;
                } catch (Throwable ex) {
                    if (Thread.interrupted()) {
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    private void processList(List<String> values){
        for(int i=0; i<values.size(); i++){
           String value = values.get(i);
           if(value.startsWith("ADD")){
               String [] vls = value.split("\\:");
               AddressBean bean = new AddressBean();
               bean.setIp(vls[1]);
               bean.setPort(Integer.parseInt(vls[2]));
               logbasedExecutor.addAppServer(bean, vls[3]);
           } else if (value.startsWith("REMOVE")){
               String [] vls = value.split("\\:");
               logbasedExecutor.removeAppServer(vls[1]);
           }
        }

    }
    private List<String> readData(Socket socket) {
        List<String> list = new ArrayList<String>();
        try {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            String userInput;
            while ((userInput = in.readLine()) != null) {
                 list.add(userInput);
            }
            in.close();
        } catch (IOException e) {
        }
       return list;
    }
}
